package com.boarsoft.boar.code.bean.biz.impl;

import java.util.List;

import org.hibernate.query.Query;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.boarsoft.bean.ReplyInfo;
import com.boarsoft.boar.code.bean.biz.BeanInfoBiz;
import com.boarsoft.boar.code.entity.BeanInfo;
import com.boarsoft.common.Util;
import com.boarsoft.common.dao.PagedResult;
import com.boarsoft.hibernate.biz.SimpleBizImpl;

@Component("beanInfoBiz")
public class BeanInfoBizImpl extends SimpleBizImpl implements BeanInfoBiz {

	/**
	 * bean信息查询：/code/bean/info/list.do
	 */
	@Override
	@Transactional(readOnly = true)
	public PagedResult<BeanInfo> list(String key, int pageNo, int pageSize) {
		StringBuilder sb = new StringBuilder();
		sb.append(" from BeanInfo r where 1=1");
		if (Util.strIsNotEmpty(key)) {
			sb.append(" and r.type like '%").append(key).append("%'");
		}
		sb.append(" order by r.id");
		List<BeanInfo> lt = this.dao.list(sb.toString(), pageNo, pageSize);
		return new PagedResult<BeanInfo>(lt.size(), lt, pageNo, pageSize);
	}

	/**
	 * bean类型名列表查询：/code/bean/info/find.do
	 */
	@Transactional(readOnly = true)
	@Override
	public ReplyInfo<Object> find(int pageNo, int pageSize) {
		return new ReplyInfo<>(true, new PagedResult<>(dao.getTotal("select count(*) from BeanInfo"),
				dao.list(BeanInfo.class, "and 1=1"), pageNo, pageSize));
	}

	/**
	 * 保存bean信息
	 * 
	 * @param beanInfo
	 *            bean信息
	 * @return 存储数据库的key
	 */
	@Transactional
	@Override
	public String save(BeanInfo beanInfo) {
		return (String) this.dao.save(beanInfo);
	}

	/**
	 * bean类型名列表查询：/code/bean/mapping/add.do
	 */
	@Transactional(readOnly = true)
	@Override
	public List<BeanInfo> findBeanInfoByType(String type) {
		Query<BeanInfo> qry = this.dao.createQuery(//
				BeanInfo.class, "from BeanInfo where type = :type");
		qry.setParameter("type", type);
		return qry.list();
	}

	@Override
	@Transactional
	public void delete(String id) {
		String w = String.format("and id='%s'", id);
		BeanInfo beanInfo = this.dao.find(BeanInfo.class, w);
		if (beanInfo != null) {
			log.info(beanInfo.toString());
			this.dao.delete(beanInfo);
		} else {
			log.info("删除数据不存在！");
		}
	}
}
